<?php
namespace app\admin\addons;
use app\admin\model\SystemMenu;

class Menu{
    /**创建菜单
     * @param array $array
     * @param string $app
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createMenu(array $array=[],$app=''){
        $obj = new Menu();
        return $obj->updateMenu($array,$app);
    }

    /**更新
     * @param array $array
     * @param string $app
     * @param int $pid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function updateMenu(array $array=[],$app='',$pid=0){
        foreach ($array as $value){
            $value['app'] = $app;
            $value['pid'] = $pid;
            $sublist = [];
            if(isset($value['sublist'])){
                $sublist = $value['sublist'];
                unset($value['sublist']);
            }
            if(isset($value['href'])&&$value['href']){
                $hasMenu = SystemMenu::where('href',$value['href'])
                    ->find();
                if(empty($hasMenu)){
                    $value['create_time'] = time();
                    $value['update_time'] = time();
                    $hasMenu = SystemMenu::create($value);
                }else{
                    $hasMenu->save($value);
                }
            }else{
                $hasMenu = SystemMenu::where('title',$value['title'])
                    ->find();
                if(empty($hasMenu)){
                    $value['create_time'] = time();
                    $value['update_time'] = time();
                    $hasMenu = SystemMenu::create($value);
                }else{
                    $hasMenu->save($value);
                }
            }
//            echo "<pre>";
//            print_r($hasMenu->toArray());
//            exit;
//            echo "<pre>";
//            print_r($sublist);
//            exit;
            if(!empty($sublist)){
                $this->updateMenu($sublist,$app,$hasMenu->id);
            }
        }
        return true;
    }

    /**禁用
     * @param string $app
     * @return bool
     */
    public static function Disable(string $app=''){
        if(empty($app)){
            return false;
        }
        $bool = SystemMenu::where('app',$app)
            ->save(['status'=>0]);
        return $bool;
    }

    /**
     * @param string $app
     * @return bool
     */
    public static function Enable(string $app=''){
        if(empty($app)){
            return false;
        }
        return SystemMenu::where('app',$app)
            ->save(['status'=>1]);
    }
}